import express, { Request, Response, NextFunction, Router } from "express";
import multer from "multer";
import {
  UserController,
  RoleController,
  KnowledgeController,
} from "../controller";

const router: Router = express.Router();

// 扩展 Request 接口
declare global {
  namespace Express {
    interface Request {
      id?: number;
      file?: Express.Multer.File;
    }
  }
}

// 内存存储配置（用于文件上传）
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB限制
  fileFilter: (
    req: express.Request,
    file: Express.Multer.File,
    cb: multer.FileFilterCallback
  ) => {
    // 检查文件类型
    if (file.mimetype.startsWith("image/")) {
      cb(null, true);
    } else {
      cb(new Error("只允许上传图片文件"));
    }
  },
});

// 中间件：验证ID参数
const validateId = (req: Request, res: Response, next: NextFunction): void => {
  const id = parseInt(req.params.id);
  if (isNaN(id)) {
    res.status(400).json({ error: "无效的ID参数" });
    return;
  }
  req.id = id;
  next();
};

// API根路径
router.get("/", (req: Request, res: Response): void => {
  const response = {
    message: "校园应急管理系统后端API服务",
    version: "1.0.0",
    endpoints: {
      users: "/api/users - 用户管理",
      roles: "/api/roles - 角色管理",
      knowledge: "/api/knowledge - 知识管理",
      events: "/api/events - 事件管理",
      volunteers: "/api/volunteers - 志愿者管理",
      notifications: "/api/notifications - 通知管理",
      files: "/api/files - 文件管理",
      system: "/api/system - 系统设置",
      health: "/health - 健康检查",
    },
  };
  res.json(response);
});

// ========== 用户管理 ==========
router.get("/users", UserController.getUsers);
router.get("/users/:id", validateId, UserController.getUserById);
router.post("/users", UserController.createUser);
router.put("/users/:id", validateId, UserController.updateUser);
router.delete("/users/:id", validateId, UserController.deleteUser);
router.patch("/users/:id/status", validateId, UserController.updateUserStatus);

// ========== 角色管理 ==========
router.get("/roles", RoleController.getRoles);
router.get("/roles/:id", validateId, RoleController.getRoleById);
router.post("/roles", RoleController.createRole);
router.put("/roles/:id", validateId, RoleController.updateRole);
router.delete("/roles/:id", validateId, RoleController.deleteRole);
router.patch(
  "/roles/:id/permissions",
  validateId,
  RoleController.updateRolePermissions
);
router.get("/permissions", RoleController.getAllPermissions);

// ========== 知识管理 ==========
router.get("/knowledge/categories", KnowledgeController.getCategories);
router.get(
  "/knowledge/categories/:id",
  validateId,
  KnowledgeController.getCategoryById
);
router.post("/knowledge/categories", KnowledgeController.createCategory);
router.put(
  "/knowledge/categories/:id",
  validateId,
  KnowledgeController.updateCategory
);
router.delete(
  "/knowledge/categories/:id",
  validateId,
  KnowledgeController.deleteCategory
);
router.patch(
  "/knowledge/categories/:id/status",
  validateId,
  KnowledgeController.toggleCategoryStatus
);
router.patch(
  "/knowledge/categories/sort",
  KnowledgeController.updateCategorySort
);

// ========== 文件上传 ==========
router.post("/upload", upload.single("file"), (req: Request, res: Response) => {
  if (!req.file) {
    return res.status(400).json({ error: "没有上传文件" });
  }

  // 这里可以添加文件保存逻辑
  const fileInfo = {
    originalName: req.file.originalname,
    mimeType: req.file.mimetype,
    size: req.file.size,
    buffer: req.file.buffer,
  };

  res.json({
    data: {
      success: true,
      data: fileInfo,
      message: "文件上传成功",
    },
  });
});

router.post(
  "/upload/multiple",
  upload.array("files", 5),
  (req: Request, res: Response) => {
    const files = req.files as Express.Multer.File[];
    if (!files || files.length === 0) {
      return res.status(400).json({ error: "没有上传文件" });
    }

    const fileInfos = files.map((file) => ({
      originalName: file.originalname,
      mimeType: file.mimetype,
      size: file.size,
    }));

    res.json({
      success: true,
      data: fileInfos,
      message: `成功上传 ${files.length} 个文件`,
    });
  }
);

// ========== 登录认证 ==========
router.post("/auth/login", async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({
        data: {
          success: false,
          message: "用户名和密码不能为空",
        },
      });
    }

    res.json({
      data: {
        success: true,
      },
    });
  } catch (error) {
    console.error("登录失败:", error);
    res.status(500).json({
      data: {
        success: false,
        message: "登录失败",
      },
    });
  }
});

export default router;
